<template>
    <el-card style="margin-top:10px">
        <el-form label-width="100px" :model="skuInfo" ref="skuFormRef" :rules="skuRules">
            <el-form-item label="SPU名称">{{ props.currentSpuInfo.spuName }}</el-form-item>
            <el-form-item label="SKU名称" prop="skuName">
                <el-input placeholder="SKU名称" v-model="skuInfo.skuName"></el-input>
            </el-form-item>
            <el-form-item label="价格(元)" prop="price">
                <el-input-number v-model="skuInfo.price" class="mx-4" :min="1" :max="100" style="width:100%"
                    controls-position="right" />
            </el-form-item>
            <el-form-item label="重量(kg)" prop="weight"> <el-input-number v-model="skuInfo.weight" class="mx-4" :min="1"
                    :max="100" style="width:100%" controls-position="right" />
            </el-form-item>
            <el-form-item label="规格描述" prop="skuDesc">
                <el-input type="textarea" :rows="4" placeholder="请描述规格" v-model="skuInfo.skuDesc"></el-input>
            </el-form-item>
            <el-form-item label="平台属性" prop="skuAttrValueList">
                <el-row :gutter="10">
                    <el-col v-for="(attr, index) in attrList" :key="attr.id" :xs="24" :sm="12" :md="8" :lg="8" :xl="6"
                        style="margin-bottom:10px">
                        <el-form-item :label="attr.attrName">
                            <el-select v-model="skuInfo.skuAttrValueList[index]" @click="clearAttrRules">
                                <el-option v-for="attrValue in attr.attrValueList" :key="attrValue.id"
                                    :label="attrValue.valueName"
                                    :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`">
                                    {{ attrValue.valueName }}
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form-item>
            <el-form-item label="销售属性" prop="skuSaleAttrValueList">
                <el-form :inline="true" label-width="100px">
                    <el-form-item v-for="(saleAttr, index) in spuSaleAttrList" :key="saleAttr.id"
                        :label="saleAttr.saleAttrName">
                        <el-select v-model="skuInfo.skuSaleAttrValueList[index]" @click="clearSaleAttrRules">
                            <el-option v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                                :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
                                :label="saleAttrValue.saleAttrValueName" :key="saleAttrValue.id">{{
                                    saleAttrValue.saleAttrValueName }}</el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-form-item>
            <el-form-item label="图片列表" prop="skuImageList">
                <el-table border style="margin-bottom:10px" :data="spuImageList" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="80"></el-table-column>
                    <el-table-column label="图片">
                        <template v-slot="{ row }">
                            <el-image style="width: 100px; height: 100px" :src="row.imgUrl" fit="fill" />
                        </template>
                    </el-table-column>
                    <el-table-column label="名称" prop="imgName"></el-table-column>
                    <el-table-column label="操作">
                        <template v-slot="{ row }">
                            <el-button v-if="row.isDefault === '0'" type="primary"
                                @click="toSetDefaultImg(row)">设置为默认图片</el-button>
                            <el-button v-else type="success">默认图片</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" @click="submitSkuForm(skuFormRef)">保存</el-button>
                <el-button>取消</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>
  
<script lang="ts">
export default {
    name: 'SkuForm'
}
</script>

<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import { ElMessage, type FormRules } from 'element-plus';
import type { SpuImageListModel, SpuInfoModel, SpuSaleAttrListModel, SpuImageModel } from '@/api/product/model/spuModel'
import type { AttrListType } from '@/api/product/model/AttrModel'
import { reqGetSpuImageListData, reqGetSpuSaleAttrListData } from '@/api/product/spu'
import { reqGetAttrListDataByCategory3Id } from '@/api/product/attr'
import { useCategoryListStore } from '@/stores/categoryList'
import { reqSaveSkuInfo } from '@/api/product/sku';
import { ShowStatus } from './types';
const categoryStore = useCategoryListStore();
const num = ref<number>(0)
const weight = ref<number>(0)
// 图片列表
const spuImageList = ref<SpuImageListModel>([])
// spu基础属性列表
const spuSaleAttrList = ref<SpuSaleAttrListModel>([])
// 平台属性列表
const attrList = ref<AttrListType>([])

//接受父组件传递的信息
const props = defineProps<{
    currentSpuInfo: SpuInfoModel; // 传入的时候， 也要添加类型约束
}>()

const emits = defineEmits(['changStatus'])

const skuFormRef = ref();


//定义提交给服务器的信息
const skuInfo = reactive({
    spuId: 0,
    category3Id: 0,
    skuName: '',
    price: 0,
    weight: 0,
    skuDesc: '',
    skuDefaultImg: '', // 默认图片的链接
    skuAttrValueList: [],
    skuImageList: [],
    skuSaleAttrValueList: []
});


onMounted(async () => {
    const id = props.currentSpuInfo.id
    const [resSpuImgageList, resSpuSaleAttrList, resAttrList] = await Promise.allSettled([reqGetSpuImageListData(id as number), reqGetSpuSaleAttrListData(id as number), reqGetAttrListDataByCategory3Id({
        category1Id: categoryStore.category1Id as number,
        category2Id: categoryStore.category2Id as number,
        category3Id: categoryStore.category3Id as number
    })])

    if (resSpuImgageList.status === 'fulfilled') {
        spuImageList.value = resSpuImgageList.value.map(item => {
            return {
                ...item,
                isDefault: '0'
            }
        })
    }

    if (resSpuSaleAttrList.status === 'fulfilled') {
        spuSaleAttrList.value = resSpuSaleAttrList.value;
    }
    if (resAttrList.status === 'fulfilled') {
        attrList.value = resAttrList.value;
    }

})
//自定义规则
const skuImageListValidate = (rule: any, value: any, callback: any) => {
    // console.log(rule, value)
    // console.log(value)
    if (!value.length) {
        return callback('请至少选择一张图片')
    }
    callback()
}

const skuAttrValueListValidate = (rule: any, value: any, callback: any) => {
    // console.log(rule,value)
    if (!value.length) {
        return callback('请选择一个平台属性')
    }
    callback()
}

const skuSaleAttrValueListValidate = (rule: any, value: any, callback: any) => {
    // console.log(rule,value)
    if (!value.length) {
        return callback('请选择一个平台属性')
    }
    callback()
}

//书写校验规则
const skuRules = reactive<FormRules>({
    skuName: [
        { required: true, message: '请输入Sku名称', trigger: 'blur' },
        { min: 1, max: 10, message: 'Sku名称在1---10之间', trigger: 'blur' }
    ],
    price: [{ required: true, message: '请输入Sku价格', trigger: 'change' }],
    weight: [{ required: true, message: '请输入Sku重量', trigger: 'change' }],
    skuDesc: [{ required: true, message: '请输入Sku描述', trigger: 'blur' }],
    skuImageList: [{ required: true, validator: skuImageListValidate, type: 'array', trigger: 'change' }],
    skuAttrValueList: [{ required: true, validator: skuAttrValueListValidate, trigger: 'change' }],
    skuSaleAttrValueList: [{ required: true, validator: skuSaleAttrValueListValidate, trigger: 'change' }]
})

//清除平台属性规则
const clearAttrRules = () => {
    skuFormRef.value?.clearValidate(['skuAttrValueList'])
}

//清除销售属性规则
const clearSaleAttrRules = () => {
    skuFormRef.value?.clearValidate(['skuSaleAttrValueList'])
}




const handleSelectionChange = (val) => {
    // console.log('vv', val)
    skuInfo.skuImageList = val
}

//设置默认图片
const toSetDefaultImg = (row: SpuImageModel) => {
    // 先将其它的设置为0
    spuImageList.value.forEach(item => {
        item.isDefault = '0';
    });

    // 将自己这个设置为1
    row.isDefault = '1';

    // 收集默认图片链接
    skuInfo.skuDefaultImg = row.imgUrl;
};


//保存
const submitSkuForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate(async valid => {
        if (valid) {
            //处理平台属性数据
            skuInfo.skuAttrValueList = skuInfo.skuAttrValueList.filter(Boolean).map(item => {
                const [attrId, attrName, valueId, valueName] = item.split(':')
                return {
                    attrId,
                    attrName,
                    valueId,
                    valueName
                }
            })
            //处理销售属性数据
            skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList.filter(Boolean).map(item => {
                const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = item.split(':')
                return {
                    saleAttrId,
                    saleAttrName,
                    saleAttrValueId,
                    saleAttrValueName
                }
            })

            skuInfo.category3Id = categoryStore.category3Id as number
            skuInfo.spuId = props.currentSpuInfo.id as number
            await reqSaveSkuInfo(skuInfo)
            ElMessage.success('添加sku成功了...')
            emits('changStatus', ShowStatus.SPU_LIST)
        } else {
            ElMessage.error('error submit!');
        }
    });
};
</script>
  
<style></style>